'use strict';

const { formatDate, formatAmount } = require("../../utils/format");
module.exports = app => {
  const { INTEGER, DATE, DECIMAL, STRING } = app.Sequelize;
  const OrderItem = app.model.define('OrderItem', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    order_id: INTEGER, // 订单ID
    order_no: STRING, // 订单号
    product_id: INTEGER, // 商品ID
    product_item_id: INTEGER, // 商品规格ID
    price: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      get() {
        return formatAmount(this.getDataValue('price'))
      }
    }, // 单价
    quantity: INTEGER,
    pay_amount: {
      type: DECIMAL(10, 2),
      defaultValue: 0,
      get() {
        return formatAmount(this.getDataValue('total_amount'))
      }
    },
    points: INTEGER,
    create_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('create_time'))
      }
    },
    update_time: {
      type: DATE,
      defaultValue: new Date(),
      get() {
        return formatDate(this.getDataValue('update_time'))
      }
    },
  },{
    tableName: 'order_item',
    timestamps: true, // 启用时间戳(createdAt, updatedAt)
    updatedAt: 'update_time', // 不想要 updatedAt
    createdAt: 'create_time', // 想要  createdAt 但是希望名称叫做 create_time
  });

  OrderItem.associate = function() {
    app.model.OrderItem.belongsTo(app.model.Order, { foreignKey: 'order_id', as: 'order' });
    app.model.OrderItem.belongsTo(app.model.Product, { foreignKey: 'product_id', as: 'product' });
    app.model.OrderItem.belongsTo(app.model.ProductItem, { foreignKey: 'product_item_id', as: 'productItem' });
  };

  return OrderItem;
};

// 建表语句带注释

// CREATE TABLE `order_item` (
//   `id` int(11) NOT NULL AUTO_INCREMENT,
//   `order_id` int(11) DEFAULT NULL COMMENT '订单ID',
//   `order_no` int(11) DEFAULT NULL COMMENT '订单号',
//   `product_id` int(11) DEFAULT NULL COMMENT '商品ID',
//   `product_item_id` int(11) DEFAULT NULL COMMENT '商品规格ID',
//   `price` decimal(10,2) DEFAULT '0.00' COMMENT '单价',
//   `quantity` int(11) DEFAULT NULL COMMENT '数量',
//   `pay_amount` decimal(10,2) DEFAULT '0.00' COMMENT '实付金额',
//   `points` int(11) DEFAULT NULL COMMENT '积分',
//   `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
//   `update_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '更新时间',
//   PRIMARY KEY (`id`)
// ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='订单商品表';
